# coding=utf-8

from application import app, redis
from common.libs.JsonLibs import bytes_to_obj
from app.model.mysql.gift import Gift as GiftMysql
from app.model.redis.gift import Gift as GiftRedis
from app.json.mysql.gift import Gift as GiftJson


def get_one(gift_id):
    redis_gift_one = redis.get(GiftRedis.gift_one.key % gift_id)
    if redis_gift_one:
        mysql_gift_one = None
    else :
        mysql_gift_one = GiftMysql.query.filter(GiftMysql.id == gift_id, GiftMysql.is_delete == 0).first()
    if mysql_gift_one:
        setInRedis(mysql_gift_one)
        gift_json = GiftJson(mysql_gift_one).getJson()
    else :
        gift_json = bytes_to_obj(redis_gift_one)
    return gift_json


def get_list():
    redis_gift_set = redis.smembers(GiftRedis.gift_set.key)
    redis_gift_list = list(redis_gift_set)
    redis_gift_list = redis_gift_list if redis_gift_list else []
    result_list = []
    if not redis_gift_list:
        mysql_gift_list = GiftMysql.query.filter(GiftMysql.is_delete == 0).all()
        for mysql_gift_one in mysql_gift_list:
            setInRedis(mysql_gift_one)
            gift_one_json = GiftJson(mysql_gift_one).getJson()
            result_list.append(gift_one_json)
        return result_list
    else:
        for gift_id in redis_gift_list:
            gift_one_json = get_one(gift_id.decode("utf-8"))
            result_list.append(gift_one_json)
        return result_list


def setInRedis(mysql_gift_one):
    redis.sadd(GiftRedis.gift_set.key, mysql_gift_one.id)
    redis.set(GiftRedis.gift_one.key % mysql_gift_one.id, GiftJson(mysql_gift_one).getJsonToRedis())
